package com.southminority.ethnic.controller.contact;

import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.service.contact.ContactService;
import com.southminority.ethnic.service.contact.CooperationFileService;
import com.southminority.ethnic.controller.contact.vo.ContactVO;
import com.southminority.ethnic.controller.contact.vo.CooperationFileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 联系留言前端API控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "📝 联系留言管理", description = "用户提交联系表单、获取合作文件等前端接口")
@RestController
@RequestMapping("/api/contact")
@CrossOrigin
public class ContactController {

    private final ContactService contactService;
    private final CooperationFileService cooperationFileService;

    public ContactController(ContactService contactService, CooperationFileService cooperationFileService) {
        this.contactService = contactService;
        this.cooperationFileService = cooperationFileService;
    }

    @PostMapping("/submit")
    @Operation(
        summary = "提交联系表单", 
        description = "用户提交联系留言表单，包括咨询、合作申请、建议反馈等",
        requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "联系表单数据", 
            required = true,
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ContactVO.class),
                examples = {
                    @ExampleObject(
                        name = "项目合作申请",
                        description = "项目合作申请示例",
                        value = """
                        {
                          "name": "张三",
                          "email": "zhangsan@example.com",
                          "phone": "13800138000",
                          "organization": "贵州民族大学",
                          "subject": "少数民族语言AI项目合作",
                          "message": "希望与实验室在少数民族语言AI领域开展深度合作，共同推进相关技术研究和应用。",
                          "contactType": "cooperation"
                        }
                        """
                    ),
                    @ExampleObject(
                        name = "学术咨询",
                        description = "学术咨询示例",
                        value = """
                        {
                          "name": "李四",
                          "email": "lisi@university.edu",
                          "phone": "13900139000",
                          "organization": "某大学语言学院",
                          "subject": "苗语语音识别技术咨询",
                          "message": "想了解实验室在苗语语音识别方面的最新研究成果，以及可能的学术交流合作机会。",
                          "contactType": "consultation"
                        }
                        """
                    )
                }
            )
        )
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "提交成功",
            content = @Content(schema = @Schema(implementation = ContactVO.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<ContactVO> submitContact(@RequestBody ContactVO contactVO, HttpServletRequest request) {
        try {
            ContactVO result = contactService.submitContact(contactVO, request);
            return R.ok(result);
        } catch (Exception e) {
            log.error("提交联系表单失败", e);
            return R.fail("提交失败: " + e.getMessage());
        }
    }

    @GetMapping("/contact-types")
    @Operation(
        summary = "获取联系类型列表", 
        description = "获取系统支持的所有联系类型，用于前端表单选择"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(
                schema = @Schema(type = "array", implementation = String.class),
                examples = @ExampleObject(
                    value = "[\"consultation\", \"cooperation\", \"suggestion\", \"complaint\", \"research\", \"other\"]"
                )
            ))
    })
    public R<List<String>> getContactTypeList() {
        try {
            List<String> contactTypes = contactService.getContactTypeList();
            return R.ok(contactTypes);
        } catch (Exception e) {
            log.error("获取联系类型列表失败", e);
            return R.fail("获取联系类型失败: " + e.getMessage());
        }
    }

    @GetMapping("/cooperation-files")
    @Operation(
        summary = "获取合作申请文件列表", 
        description = "获取所有可用的合作申请文件，包括申请表模板、说明文档等"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(type = "array", implementation = CooperationFileVO.class)))
    })
    public R<List<CooperationFileVO>> getCooperationFiles() {
        try {
            List<CooperationFileVO> files = cooperationFileService.getActiveFiles();
            return R.ok(files);
        } catch (Exception e) {
            log.error("获取合作申请文件列表失败", e);
            return R.fail("获取合作申请文件失败: " + e.getMessage());
        }
    }

    @GetMapping("/cooperation-files/default")
    @Operation(
        summary = "获取默认合作申请表", 
        description = "获取系统推荐的默认合作申请表模板"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(implementation = CooperationFileVO.class))),
        @ApiResponse(responseCode = "404", description = "未找到默认文件")
    })
    public R<CooperationFileVO> getDefaultCooperationFile() {
        try {
            CooperationFileVO file = cooperationFileService.getDefaultFile();
            return R.ok(file);
        } catch (Exception e) {
            log.error("获取默认合作申请表失败", e);
            return R.fail("获取默认合作申请表失败: " + e.getMessage());
        }
    }

    @GetMapping("/cooperation-files/download/{id}")
    @Operation(
        summary = "下载合作申请文件", 
        description = "根据文件ID下载合作申请相关文件，支持PDF、Word等格式"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "下载成功", 
            content = @Content(mediaType = "application/octet-stream")),
        @ApiResponse(responseCode = "404", description = "文件不存在"),
        @ApiResponse(responseCode = "500", description = "下载失败")
    })
    public void downloadCooperationFile(
            @Parameter(description = "合作文件ID", example = "1", required = true) 
            @PathVariable Long id,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            cooperationFileService.downloadFile(id, request, response);
        } catch (Exception e) {
            log.error("下载合作申请文件失败: id={}", id, e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/test")
    @Operation(
        summary = "测试接口连通性", 
        description = "测试联系留言服务是否正常运行"
    )
    @ApiResponse(responseCode = "200", description = "服务正常",
        content = @Content(
            schema = @Schema(type = "string"),
            examples = @ExampleObject(value = "联系留言服务正常运行")
        ))
    public R<String> test() {
        return R.ok("联系留言服务正常运行");
    }
} 